'use strict';

const Controller = require('egg').Controller;

class BaseController extends Controller {
  success(data = {}, count) {
    const { ctx } = this;
    ctx.body = {
      status: 200,
      data,
      count,
      success: true,
    };
  }

  error(message = '服务器异常') {
    const { ctx } = this;
    ctx.body = {
      status: 500,
      message,
      success: false,
    };
  }

  /**
   * @description 获取service
   * */
  _getService() {
    return this.service[this._service];
  }

  /**
   * @description 删除数据模板
   * @param msg 错误信息
   * */
  async _destory(msg = '删除数据失败') {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await this._getService().destory(+id);
    if (result) {
      this.success();
    } else {
      this.error(msg);
    }
  }

  /**
   * @description 获取单个数据模板
   * @param msg 错误信息
   * */
  async _show(msg = '获取数据失败') {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await this._getService().findOne({ id: +id });
    if (result) {
      this.success(result);
    } else {
      this.error(msg);
    }
  }

  /**
   * @description 获取全部模板
   * @param msg 错误信息
   * */
  async _all(msg = '获取数据失败') {
    const result = await this._getService().findAll();
    if (result) {
      this.success(result);
    } else {
      this.error(msg);
    }
  }
}

module.exports = BaseController;
